<template>
  <div class="app-container" style="overflow: hidden">
    <div class="header" v-if="!isCheck">
      <el-button
        size="mini"
        icon="el-icon-plus"
        type="primary"
        @click="onadd"
        v-hasPermi="[proveType == 1 ? 'casemanage1:add' : 'casemanage:add']"
        >新增
      </el-button>
      <el-button
        size="mini"
        type="primary"
        icon="el-icon-upload"
        @click="handleImport"
        v-hasPermi="['casemanage:add']"
        >导入
      </el-button>
      <a
        href="/template/传君OA案件导入模版.xlsx"
        download="传君OA案件导入模版.xlsx"
        target="_blank"
        style="margin: 0 10px"
        v-hasPermi="['casemanage:add']"
      >
        <el-button icon="el-icon-download" size="mini" type="default"
          >下载模板
        </el-button>
      </a>
      <el-button
        size="mini"
        icon="el-icon-delete"
        :loading="loading"
        :disabled="!multipleSelection.length"
        v-hasPermi="[proveType == 1 ? 'casemanage1:del' : 'casemanage:del']"
        @click="onDelAll"
        type="danger"
      >
        批量删除
      </el-button>
      <el-button
        size="mini"
        type="primary"
        icon="el-icon-download"
        @click="onexportData"

        :disabled="!multipleSelection.length"
        >导出
      </el-button>
      <el-button
        size="mini"
        type="primary"
        icon="el-icon-s-order"
        @click="onarchive"
        v-hasPermi="[proveType == 1 ? 'casemanage1:onarchive' : 'casemanage:onarchive']"
        :disabled="!multipleSelection.length"
        >归档
      </el-button>
    </div>
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true">
      <el-form-item label="案件编号" prop="caseNo">
        <el-input
          v-model="queryParams.caseNo"
          placeholder="案件编号"
          clearable
          style="width: 150px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="案件名称" prop="caseName">
        <el-input
          v-model="queryParams.caseName"
          placeholder="案件名称"
          clearable
          style="width: 150px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户名称" prop="customerName">
        <el-input
          v-model="queryParams.customerName"
          placeholder="客户名称"
          clearable
          style="width: 150px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="承办人" prop="customerName">
        <el-input
          v-model="queryParams.handlerName"
          placeholder="承办人"
          clearable
          style="width: 150px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="案件分类" prop="categoryId">
        <el-select
          clearable
          v-model="queryParams.categoryId"
          placeholder="请选择案件分类"
        >
          <el-option
            :label="item.label"
            :value="item.value"
            v-for="(item, index) of dict.type.sys_carage_type"
            :key="index + 'Source'"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="案件状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="案件状态"
          clearable
        >
          <el-option
            :label="item.label"
            :value="item.value"
            v-for="(item, index) of dict.type.case_state"
            :key="index + 'status'"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="审批状态" prop="status">
        <el-select
          v-model="queryParams.auditStatus"
          placeholder="审批状态"
          clearable
        >
          <el-option
            :label="item.label"
            :value="item.value"
            v-for="(item, index) of dict.type.audit_status"
            :key="index + 'status'"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="receiptYear">
        <el-date-picker
          v-model="queryParams.receiptYear"
          type="year"
          placeholder="请选择"/>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索
        </el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置
        </el-button>
      </el-form-item>
    </el-form>
    <el-table
      @selection-change="handleSelectionChange"
      v-loading="loading"
      :data="roleList"
      :height="tableHeight"
    >
      <el-table-column
        type="selection"
        :selectable="selectable"
        v-if="!isCheck"
        width="55"
      >
      </el-table-column>

      <el-table-column
        label="案件编号"
        prop="caseNo"
        min-width="240"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="案件名称"
        prop="caseName"
        :show-overflow-tooltip="true"
        width="150"
      >
        <template slot-scope="scope">
          <div
            v-if="scope.row.isConflict == '1' && proveType == 2"
            style="color: red"
          >
            {{ scope.row.caseName }}
          </div>
          <span v-else>
            {{ scope.row.caseName }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        label="案件分类"
        prop="status"
        width="150"
        :show-overflow-tooltip="true"
      >
        <template slot-scope="scope">
          {{ scope.row.categoryName
          }}{{
            scope.row.subCategoryName ? ">>" + scope.row.subCategoryName : ""
          }}
          {{
            scope.row.thirdCategoryName
              ? ">>" + scope.row.thirdCategoryName
              : ""
          }}
        </template>
      </el-table-column>
      <el-table-column
        label="收案时间"
        :show-overflow-tooltip="true"
        width="150"
        prop="receiptDate"
      />
      <el-table-column
        label="客户"
        :show-overflow-tooltip="true"
        width="150"
        prop="customerName"
      />
      <el-table-column
        label="对方当事人"
        :show-overflow-tooltip="true"
        width="150"
        prop="targetPartyName"
      />
      <el-table-column
        label="承办人员"
        :show-overflow-tooltip="true"
        width="150"
        prop="handlerName"
      />
      <el-table-column
        width="150"
        label="合同状态"
        prop="contractStatus"
        :formatter="formatter"
      />
      <el-table-column
        label="受理机构"
        :show-overflow-tooltip="true"
        prop="acceptOrgName"
        width="150"
      />
      <el-table-column
        label="受理案号"
        :show-overflow-tooltip="true"
        prop="acceptOrgNo"
        width="150"
      />
      <el-table-column
        label="案件状态"
        :show-overflow-tooltip="true"
        prop="roleSort"
        width="150"
      >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.case_state" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="审批结果" prop="auditStatus">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.audit_status"
            :value="scope.row.auditStatus"
          />
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        fixed="right"
        :width="!isCheck ? '230' : '130'"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope" >
          <template v-if="scope.row.status != 4">
            <div v-if="!isCheck">
              <el-button
                size="mini"
                type="text"
                @click="onedit(scope.row)"
                v-hasPermi="[
                  proveType == 1 ? 'casemanage1:edit' : 'casemanage:edit',
                ]"
                v-if="
                  ![2, 3].includes(scope.row.status) && scope.row.archived != 1
                "
                >编辑
              </el-button>
              <el-button
                size="mini"
                type="text"
                @click="ondel(scope.row)"
                v-hasPermi="[
                  proveType == 1 ? 'casemanage1:del' : 'casemanage:del',
                ]"
                v-if="
                  ![2, 3].includes(scope.row.status) && scope.row.archived != 1
                "
                :disabled="scope.row.auditStatus == 0"
                >删除
              </el-button>
              <el-button
                size="mini"
                type="text"
                @click="openModal('closeModalVue', scope.row)"
                v-hasPermi="[
                  proveType == 1 ? 'casemanage1:close' : 'casemanage:close',
                ]"
                v-if="scope.row.status == 1 && scope.row.archived != 1"
                >结案
              </el-button>
              <!--结案只有办理中才展示-->
              <!--财务信息只有结案销案，，2,3的时候才展示-->
              <el-button
                size="mini"
                type="text"
                @click="openModal('finance', scope.row)"
                v-hasPermi="[
                  proveType == 1 ? 'casemanage1:finance' : 'casemanage:finance',
                ]"
                v-if="
                  [2, 3].includes(scope.row.status) && scope.row.archived != 1
                "
                >财务信息
              </el-button>
              <el-button
                size="mini"
                type="text"
                @click="openModal('casehandingModalVue', scope.row)"
                v-hasPermi="[
                  proveType == 1
                    ? 'casemanage1:casehanding'
                    : 'casemanage:casehanding',
                ]"
                v-if="
                  scope.row.status == 0 &&
                  scope.row.auditStatus == 1 &&
                  scope.row.archived != 1
                "
                >案件办理
              </el-button>
              <el-button
                size="mini"
                type="text"
                @click="openModal('detailModalVue', scope.row)"
                >查看
              </el-button>
              <el-button
                size="mini"
                v-if="scope.row.auditStatus == 1 && scope.row.archived != 1"
                type="text"
                @click="onExport(scope.row)"
                >打印</el-button
              >
              <el-button
                size="mini"
                v-hasPermi="[proveType == 1 ?  'casemanage1:back' :'casemanage:back']"
                type="text"
                @click="onShowBack(scope.row)"
                v-if="scope.row.auditStatus != 6 && scope.row.archived != 1"
                >退案</el-button
              >
            </div>
            <div v-else>
              <el-button
                size="mini"
                type="text"
                @click="openModal('detailModalVue', scope.row, 2)"
                v-if="proveType == 3 && scope.row.archived != 1"
                :class="{ isConflict: scope.row.isConflict == 1 }"
                >审核
              </el-button>
              <template>
                <el-button
                  size="mini"
                  type="text"
                  @click="openModal('detailModalVue', scope.row, 2)"
                  v-hasPermi="[
                    proveType == 1 ? 'casemanage1:shenhe' : 'casemanage:shenhe',
                  ]"
                  v-if="scope.row.auditStatus == 0 && scope.row.archived != 1"
                  :class="{ isConflict: scope.row.isConflict == 1 }"
                  >审核<span v-if="scope.row.isConflict == 1">!</span>
                </el-button>
                <el-button
                  size="mini"
                  v-else
                  type="text"
                  @click="openModal('detailModalVue', scope.row, 3)"
                  >查看
                </el-button>
              </template>
            </div>
          </template>
          <template  v-else>
            <el-button
              size="mini"
              type="text"
              @click="openModal('detailModalVue', scope.row)"
              >查看
            </el-button>
            <el-button
                size="mini"
                v-if="scope.row.auditStatus == 1"
                type="text"
                @click="onExport(scope.row)"
                >打印</el-button
              >
          </template>
        </template>

      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <detailModalVue
      ref="detailModalVue"
      @submit="handleQuery"
      :proveType="proveType"
    />
    <closeModalVue ref="closeModalVue" @submit="handleQuery" />
    <finance ref="finance" @submit="handleQuery" />
    <casehandingModalVue ref="casehandingModalVue" @submit="handleQuery" />
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="450px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :on-error="handleFileError"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" />
            是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <a
            href="/static/fs/template/case-template.xlsx"
            style="font-size: 12px; vertical-align: baseline"
            download="案件导入模板.xlsx"
            target="_blank"
            >下载模板</a
          >
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="submitFileForm"
          :loading="upload.isUploading"
          >确 定</el-button
        >
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <backCase ref="backCase"></backCase>
  </div>
</template>

<script>
import { list } from "@/api/system/case";
import {
  caselist,
  deleCase,
  batchRemove,
  exportdata,
  archivefile,
} from "@/api/case/case";
import finance from "./financeModal.vue";
import detailModalVue from "./detailModal.vue";
import closeModalVue from "./closeModal.vue";
import casehandingModalVue from "./casehandingModal.vue";
import { getToken } from "@/utils/auth";
import { download as $download } from "@/utils/request";
import backCase from "./backCase.vue";
import dayjs from 'dayjs'
export default {
  name: "sealmanage",
  dicts: [
    "sys_normal_disable",
    "case_source",
    "approval_status",
    "case_state",
    "audit_status",
    "sys_carage_type",
  ],
  components: {
    detailModalVue,
    closeModalVue,
    finance,
    casehandingModalVue,
    backCase,
  },
  computed: {
    tableHeight() {
      return this.$store.state.app.clientHeight - 50;
    },
    isCheck() {
      return ["2", "3"].includes(this.proveType);
    },
  },
  data() {
    return {
      uploading: false,
      multipleSelection: [],
      // 遮罩层
      loading: true,
      // 选中数组
      total: 0,
      // 角色表格数据
      roleList: [],
      dateRange: [], //搜索时间
      tree: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        caseNo: undefined,
        caseName: undefined,
        customerName: undefined,
        handlerName: "",
        categoryId: "",
        status: "",
        auditStatus: "",
        orderByColumn: "updateTime",
        isAsc: "desc",
        eceiptYear: ""
      },
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/case/importData",
      },
    };
  },
  props: {
    proveType: {
      type: String,
      default: "0", // 0案件管理，1我的案件，2案件审核, 3案件退回审批
    },
  },
  created() {
    this.getList();
    this.getTree();
    this.$root.$on("notice:case", (e) => {
      console.log("on notice =>>>>", e);
      this.$nextTick(() => {
        this.openModal("detailModalVue", e, 3);
      });
    });
  },
  mounted() {
    console.log('this.$modal')
    console.log(this.$modal)
  },
  methods: {
    onShowBack(row) {
      this.$refs.backCase.onShow(row);
    },
    //导出新增
    onexportData() {
      let ids = this.multipleSelection.map((item) => item.id);
      exportdata(ids).then((res) => {
        const downloadElement = document.createElement("a");
        const href = window.URL.createObjectURL(res); // 创建下载的链接
        downloadElement.href = href;
        downloadElement.download = "附件.xls"; // 下载后文件名
        document.body.appendChild(downloadElement);
        downloadElement.click();
        document.body.removeChild(downloadElement);
        URL.revokeObjectURL(href);
        this.onClearChoose();
      });
    },
    onClearChoose() {
      this.$refs.table.clearSelection();
      this.multipleSelection = [];
    },
    //归档
    onarchive() {
      if (this.multipleSelection.length < 1) {
        this.$message.error("请选择需要归档的案件");
      } else {
        this.$prompt("请输入归档号",'提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }).then(({ value  }) => {
          let ids = this.multipleSelection.map((item) => {
            return item.id;
          });
          archivefile({ ids: ids, archiveNo: value  }).then((res) => {
            console.log(res);
            this.resetQuery();
            this.onClearChoose();
          });
        });
      }
    },
    onDelAll() {
      // 批量删除功能
      this.$modal.confirm("是否确认删除").then(() => {
        this.loading = true;
        const ids = this.multipleSelection.map((v) => v.id);
        batchRemove(ids)
          .then((res) => {
            if (ids.length === this.roleList.length) {
              let page = this.queryParams;
              page--;
              this.queryParams.page = page > 1 ? page : 1;
            }
            this.getList();
            this.onClearChoose();
          })
          .finally(() => {
            this.loading = false;
          });
      });
    },
    selectable(row) {
      return row.auditStatus != 0;
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    getTree() {
      //获取案件分类
      list().then((res) => {
        console.log(res);
        this.tree = res.data;
      });
    },
    formatter(row) {
      switch (row.contractStatus) {
        case 0:
          return "未提交";
        case 1:
          return "已提交";
        default:
          return row.contractStatus;
      }
    },
    /** 查询角色列表 */
    getList() {
      this.loading = true;
      let { receiptYear } =  this.queryParams
      let params = {
        orderByColumn: "updateTime",
        isAsc: "desc",
        auditor: this.proveType === "0" ? "0" : "1",
        proveType: this.proveType,
        receiptYear: receiptYear ? dayjs(receiptYear).format('YYYY') : ''
      };
      this.multipleSelection = [];
      caselist({
        ...this.addDateRange(this.queryParams, this.dateRange),
        ...params,
      }).then((response) => {
        this.roleList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
      // this.$tab.refreshPage({ path: "caseManage" });
      // this.$tab.openPage("编辑案件", "addcaseManage");
    },
    //下载
    download(row, type) {
      let resource = `${row.url}`;
      this.$download.resource(resource);
    },
    handleImport() {
      this.upload.title = "案件导入";
      this.upload.open = true;
    },
    //新增
    onadd() {
      this.$router.push({
        path: "/caseManage/addcaseManage",
        query: { title: "新增案件管理", type: "add" },
      });
    },
    //编辑
    onedit(row) {
      this.$router.push({
        path: "/caseManage/addcaseManage",
        query: {
          title: "编辑案件管理",
          type: "edit",
          id: row.id,
          auditStatus: row.auditStatus,
        },
      });
    },
    onExport(row) {
      $download(`/system/case/export/${row.id}`, {}, `${row.caseNo}.pdf`);
    },
    //删除
    ondel(row) {
      this.$modal
        .confirm("是否确认删除" + (row.caseName || '')  + '的数据项？')
        .then(() => {
          deleCase(row.id).then((res) => {
            this.$modal.msgSuccess("删除成功");
            this.getList();
          });
        })
        .catch(() => {});
    },
    //财务信息
    openModal(refname, row, type = 1) {
      this.$refs[refname].open(row, type);
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download(
        "system/case/importTemplate",
        {},
        `user_template_${new Date().getTime()}.xlsx`
      );
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.uploading = false;
      this.getList();
    },
    handleFileError(error, file, fileList) {
      console.log(error, file, fileList);
    },
    // 提交上传文件
    submitFileForm() {
      this.uploading = true;
      this.$refs.upload.submit();
    },
  },
};
</script>
<style lang="scss" scoped>
.header {
  margin-bottom: 20px;
}
.isConflict {
  color: red;
}
</style>
